/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package sys.screen;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.sql.SQLException;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.swing.ImageIcon;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.SwingConstants;
import javax.swing.SwingWorker;
import javax.swing.UIManager;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import sys.bean.PedidoBean;
import sys.bean.UsuarioBean;
import sys.dao.PedidoDao;
import sys.dao.UsuarioDao;
import sys.utils.Mensagens;
import sys.utils.Utils;
import static sys.utils.Utils.escClose;

/**
 *
 * @author Cesar Daniel
 */
public class UIAnalisaDescontos extends javax.swing.JDialog {

    private UITelaPrincipal pai;
    private List<UsuarioBean> listaVendedores;
    SimpleDateFormat formBancoSpac = new SimpleDateFormat("yyyyMMdd");
    NumberFormat formatoMoeda = NumberFormat.getCurrencyInstance();

    /**
     * Creates new form UIAnalisaDescontos
     */
    public UIAnalisaDescontos() {
        initComponents();
    }

    public UIAnalisaDescontos(java.awt.Dialog parent, boolean modal) {
        super(parent, modal);
        initComponents();
        setLocationRelativeTo(null);
        setResizable(false);
        escClose(this);
        dataInicial.setDate(new Date());
        dataFinal.setDate(new Date());
        this.setIconImage(new ImageIcon(getClass().getResource("/sys/picture/icon.png")).getImage());
        UIManager.put("Table.alternateRowColor", new java.awt.Color(230, 255, 255));
        atuComboVendedores();
        Utils.maximizarDialog(this);
    }

    public UIAnalisaDescontos(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        setLocationRelativeTo(null);
        setResizable(false);
        escClose(this);
        dataInicial.setDate(new Date());
        dataFinal.setDate(new Date());
        this.setIconImage(new ImageIcon(getClass().getResource("/sys/picture/icon.png")).getImage());
        UIManager.put("Table.alternateRowColor", new java.awt.Color(230, 255, 255));
        atuComboVendedores();
        Utils.maximizarDialog(this);
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jpDataEntrada = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        dataInicial = new com.toedter.calendar.JDateChooser("dd/MM/yyyy", "##/##/#####", '_');
        dataFinal = new com.toedter.calendar.JDateChooser("dd/MM/yyyy", "##/##/#####", '_');
        cbVendedor = new javax.swing.JComboBox();
        jLabel3 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tabela = new javax.swing.JTable();
        jPanel4 = new javax.swing.JPanel();
        btnSalvar = new javax.swing.JButton();
        btnAnalisar1 = new javax.swing.JButton();
        btnSair = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("ANALISE DE DESCONTOS");

        jPanel1.setBackground(new java.awt.Color(255, 255, 255));

        jpDataEntrada.setBackground(new java.awt.Color(255, 255, 255));
        jpDataEntrada.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "SELECIONE DADOS:", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Calibri", 0, 10))); // NOI18N

        jLabel1.setFont(new java.awt.Font("Calibri", 0, 11)); // NOI18N
        jLabel1.setText("DATA INICIAL:");

        jLabel2.setFont(new java.awt.Font("Calibri", 0, 11)); // NOI18N
        jLabel2.setText("DATA FINAL:");

        dataInicial.setFont(new java.awt.Font("Calibri", 0, 14)); // NOI18N

        dataFinal.setFont(new java.awt.Font("Calibri", 0, 14)); // NOI18N

        cbVendedor.setFont(new java.awt.Font("Calibri", 0, 12)); // NOI18N

        jLabel3.setFont(new java.awt.Font("Calibri", 0, 11)); // NOI18N
        jLabel3.setText("VENDEDOR:");

        javax.swing.GroupLayout jpDataEntradaLayout = new javax.swing.GroupLayout(jpDataEntrada);
        jpDataEntrada.setLayout(jpDataEntradaLayout);
        jpDataEntradaLayout.setHorizontalGroup(
            jpDataEntradaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpDataEntradaLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jpDataEntradaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(dataInicial, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jpDataEntradaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(dataFinal, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jpDataEntradaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3)
                    .addComponent(cbVendedor, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jpDataEntradaLayout.setVerticalGroup(
            jpDataEntradaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jpDataEntradaLayout.createSequentialGroup()
                .addGroup(jpDataEntradaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jpDataEntradaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(cbVendedor, javax.swing.GroupLayout.DEFAULT_SIZE, 25, Short.MAX_VALUE)
                    .addComponent(dataFinal, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(dataInicial, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );

        tabela.setAutoCreateRowSorter(true);
        tabela.setFont(new java.awt.Font("Calibri", 0, 12)); // NOI18N
        tabela.setForeground(new java.awt.Color(51, 51, 255));
        tabela.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "PEDIDO", "VENDEDOR", "DATA", "CLIENTE", "TOTAL", "DESCONTO", "VALOR FINAL", "% DESCONTO"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tabela.setGridColor(new java.awt.Color(204, 204, 204));
        tabela.getTableHeader().setReorderingAllowed(false);
        tabela.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tabelaMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tabela);
        if (tabela.getColumnModel().getColumnCount() > 0) {
            tabela.getColumnModel().getColumn(3).setPreferredWidth(230);
        }

        jPanel4.setBackground(new java.awt.Color(255, 255, 255));
        jPanel4.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(204, 204, 204), 1, true));

        btnSalvar.setFont(new java.awt.Font("Calibri", 0, 13)); // NOI18N
        btnSalvar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/sys/picture/find-2.png"))); // NOI18N
        btnSalvar.setText("GERAR");
        btnSalvar.setPreferredSize(new java.awt.Dimension(120, 30));
        btnSalvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSalvarActionPerformed(evt);
            }
        });
        jPanel4.add(btnSalvar);

        btnAnalisar1.setFont(new java.awt.Font("Calibri", 0, 13)); // NOI18N
        btnAnalisar1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/sys/picture/edit.png"))); // NOI18N
        btnAnalisar1.setText("ANALISAR");
        btnAnalisar1.setMaximumSize(new java.awt.Dimension(75, 25));
        btnAnalisar1.setMinimumSize(new java.awt.Dimension(75, 25));
        btnAnalisar1.setPreferredSize(new java.awt.Dimension(120, 30));
        btnAnalisar1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAnalisar1ActionPerformed(evt);
            }
        });
        jPanel4.add(btnAnalisar1);

        btnSair.setFont(new java.awt.Font("Calibri", 0, 13)); // NOI18N
        btnSair.setIcon(new javax.swing.ImageIcon(getClass().getResource("/sys/picture/sair.png"))); // NOI18N
        btnSair.setText("SAIR");
        btnSair.setPreferredSize(new java.awt.Dimension(120, 30));
        btnSair.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSairActionPerformed(evt);
            }
        });
        jPanel4.add(btnSair);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 940, Short.MAX_VALUE)
                    .addComponent(jPanel4, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jpDataEntrada, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jpDataEntrada, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 329, Short.MAX_VALUE)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(0, 0, 0))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(0, 0, 0))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void tabelaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tabelaMouseClicked
        if (evt.getClickCount() == 2) {
            UIAnalisaPedidos uiap = new UIAnalisaPedidos(this, true);
            uiap.txPedido.setText(tabela.getValueAt(tabela.getSelectedRow(), 0).toString());
            uiap.setVisible(true);
        }

        if ((evt.getModifiers() & java.awt.event.MouseEvent.BUTTON3_MASK) != 0) {
            JPopupMenu menu = new JPopupMenu();
            JMenuItem item = new JMenuItem("ANALISAR PEDIDO");
            item.setIcon(new javax.swing.ImageIcon(getClass().getResource("/sys/picture/edit.png")));
            menu.add(item);
            item.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    chamaAnaPedidos();
                }
            });
            menu.show(evt.getComponent(), evt.getX(), evt.getY());
        }

    }//GEN-LAST:event_tabelaMouseClicked

    private void btnSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalvarActionPerformed
        final BarraProgresso pb = new BarraProgresso(this);
        SwingWorker worker = new SwingWorker() {

            @Override
            protected Object doInBackground() throws Exception {
                pb.gerarJanela();
                atualizaTabela();
                return null;
            }

            @Override
            protected void done() {
                pb.fechar();
            }
        };
        worker.execute();
    }//GEN-LAST:event_btnSalvarActionPerformed

    private void btnSairActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSairActionPerformed
        this.dispose();
    }//GEN-LAST:event_btnSairActionPerformed

    private void btnAnalisar1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAnalisar1ActionPerformed

        if (tabela.getSelectedRow() <= 0) {
            Mensagens.msgAtencao("selecione pedido");
        } else {
            UIAnalisaPedidos uiap = new UIAnalisaPedidos(this, true);
            uiap.txPedido.setText(tabela.getValueAt(tabela.getSelectedRow(), 0).toString());
            uiap.setVisible(true);
        }

    }//GEN-LAST:event_btnAnalisar1ActionPerformed

    private void atuComboVendedores() {
        try {

            cbVendedor.removeAllItems();
            cbVendedor.addItem("<< TODOS OS VENDEDORES >>");
            listaVendedores = UsuarioDao.getListaComboVendedores();

            for (UsuarioBean usu : listaVendedores) {
                cbVendedor.addItem(usu.getCodigo() + " - " + usu.getNome());
            }
        } catch (IOException | SQLException ex) {
            Mensagens.msgErro("erro\n" + ex.getMessage());
        }
    }

    private void chamaAnaPedidos() {
        UIAnalisaPedidos uiap = new UIAnalisaPedidos(this, true);
        uiap.txPedido.setText(tabela.getValueAt(tabela.getSelectedRow(), 0).toString());
        uiap.setVisible(true);
    }

    private void atualizaTabela() {

        DefaultTableModel modelo = (DefaultTableModel) tabela.getModel();
        modelo.setNumRows(0);
        String idVendedor = "";

        if (cbVendedor.getSelectedIndex() != 0) {
            idVendedor = listaVendedores.get(cbVendedor.getSelectedIndex() - 1).getCodigo();
        }

        try {
            //formatoMoeda.format(pedido.getdEspecial())
            for (PedidoBean pedido : PedidoDao.descontoPeriodo(formBancoSpac.format(dataInicial.getDate()), formBancoSpac.format(dataFinal.getDate()), idVendedor)) {
                modelo.addRow(new Object[]{
                    pedido.getPedido(), pedido.getUsuario().getNome(), Utils.dataCorreta(pedido.getData()), pedido.getCliente().getNome(),
                    formatoMoeda.format(pedido.getvTotal()).replace("R$", ""), formatoMoeda.format(pedido.getdGerente()).replace("R$", ""),
                    formatoMoeda.format(pedido.getvFinal()).replace("R$", ""), formatoMoeda.format(pedido.getPorcentagem()).replace("R$", "") + " %"
                });
            }

            DefaultTableCellRenderer centralizado = new DefaultTableCellRenderer();

            centralizado.setHorizontalAlignment(SwingConstants.CENTER);
            tabela.getColumnModel().getColumn(0).setCellRenderer(centralizado);
            tabela.getColumnModel().getColumn(2).setCellRenderer(centralizado);
            tabela.getColumnModel().getColumn(4).setCellRenderer(centralizado);
            tabela.getColumnModel().getColumn(5).setCellRenderer(centralizado);
            tabela.getColumnModel().getColumn(6).setCellRenderer(centralizado);
            tabela.getColumnModel().getColumn(7).setCellRenderer(centralizado);

        } catch (SQLException | IOException ex) {
            Mensagens.msgErro("erro\n" + ex.getMessage());
        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAnalisar1;
    private javax.swing.JButton btnSair;
    private javax.swing.JButton btnSalvar;
    private javax.swing.JComboBox cbVendedor;
    private com.toedter.calendar.JDateChooser dataFinal;
    private com.toedter.calendar.JDateChooser dataInicial;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JPanel jpDataEntrada;
    private javax.swing.JTable tabela;
    // End of variables declaration//GEN-END:variables
}
